package com.newlink.building.record.fragment

import android.content.Context
import android.util.Log
import android.view.LayoutInflater
import android.view.View
import android.widget.ImageView
import android.widget.LinearLayout
import android.widget.TextView
import androidx.fragment.app.Fragment
import androidx.fragment.app.FragmentManager
import androidx.fragment.app.FragmentPagerAdapter
import androidx.recyclerview.widget.RecyclerView
import androidx.viewpager.widget.ViewPager
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.google.android.material.tabs.TabLayout
import com.newlink.building.common_base.base.BaseFragment
import com.newlink.building.common_base.base.BaseMvpFragment
import com.newlink.building.common_base.event.CaptureExitEditEvent
import com.newlink.building.common_base.event.EnterEditEvent
import com.newlink.building.common_base.event.MessageEvent
import com.newlink.building.common_base.event.Base_QuickRecordEvent
import com.newlink.building.common_base.event.RecordReadCountActionEvent
import com.newlink.building.common_base.event.ScreenShotDeleteEvent
import com.newlink.building.common_base.event.ScreenShotSelectEvent
import com.newlink.building.common_base.event.TYPE_APP_BACK_PRESS
import com.newlink.building.common_base.event.TYPE_APP_SCREENSHOT_EDIT_OFF
import com.newlink.building.common_base.event.UpdateButtonEvent
import com.newlink.building.common_base.utils.NLog
import com.newlink.building.common_base.utils.GarbageUtils
import com.newlink.building.common_base.widget.CustomDialog
import com.newlink.building.common_base.widget.SpaceItemDecoration
import com.newlink.building.record.R
import com.newlink.building.record.adapter.Module_Record_RecordDeviceDialogAdapter
import com.newlink.building.record.bean.Module_Record_RecordDeviceDialogBean
import com.newlink.building.record.databinding.FragmentRecordBinding
import com.newlink.building.record.mvp.Module_Record_RecordPresenter
import com.newlink.building.record.mvp.contract.Module_Record_RecordContract
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationHelper
import com.newlink.building.obfuscation.Module_Obfuscation_ObfuscationInvoker
import org.greenrobot.eventbus.EventBus
import org.greenrobot.eventbus.Subscribe
import org.greenrobot.eventbus.ThreadMode
import java.util.Locale


/**
 * @author wangyang
 * @date 2022/9/23
 * @description 记录页面的Fragment
 */
class Module_Record_RecordFragment(var initialReadCountEvent: RecordReadCountActionEvent? = null) :
    BaseMvpFragment<Module_Record_RecordContract.View, Module_Record_RecordContract.Presenter>(), Module_Record_RecordContract.View {

    // 视图绑定实例
    private lateinit var binding: FragmentRecordBinding

    // 记录设备列表数据
    private lateinit var recordDeviceList: ArrayList<Module_Record_RecordDeviceDialogBean>

    // 记录Fragment列表
    private val recordFragments = ArrayList<Fragment>()

    // 是否全选状态
    private var isAllItemsSelected = true

    // Companion object 用于提供Fragment实例，支持传入初始事件
    companion object {
        private const val TAG = "RecordFragment"
        fun getInstance(event: RecordReadCountActionEvent? = null): Module_Record_RecordFragment =
            Module_Record_RecordFragment(event)
    }

    /**
     * 初始化块，用于处理传入的初始事件
     */
    init {
        this.initialReadCountEvent = initialReadCountEvent
    }

    /**
     * 创建Presenter实例
     */
    override fun createPresenter(): Module_Record_RecordContract.Presenter {
        return Module_Record_RecordPresenter()
    }

    /**
     * 绑定布局文件
     */
    override fun attachLayoutRes(): View {
        binding = FragmentRecordBinding.inflate(layoutInflater)
        return binding.root
    }

    /**
     * 初始化视图组件和设置监听器
     */
    override fun initView(view: View) {
        super.initView(view)
        // 记录页面初始化时的混淆
        Module_Obfuscation_ObfuscationHelper.onMethodEnter("RecordFragment", "initView")
        Module_Obfuscation_ObfuscationInvoker.invokeRandom(System.currentTimeMillis())

        setupToolbarViews()
        initializeDeviceList()
        setupClickListeners()
        setupViewPagerWithTabs()
        initialReadCountEvent?.let { updateTabUnreadDot(it) }
    }

    /**
     * 配置顶部工具栏的显示状态和文本
     */
    private fun setupToolbarViews() {
        activity?.findViewById<LinearLayout>(R.id.ll_title_bar_back)?.visibility = View.INVISIBLE
        activity?.findViewById<ImageView>(R.id.iv_title_bar_right)
            ?.setBackgroundResource(R.mipmap.title_bar_delete)
        activity?.findViewById<ImageView>(R.id.iv_title_bar_right)?.visibility = View.GONE
        activity?.findViewById<TextView>(R.id.tv_title_bar_center)?.text =
            resources.getText(R.string.record_title)
        activity?.findViewById<ImageView>(R.id.iv_title_bar_center)?.visibility = View.GONE
    }

    /**
     * 初始化记录设备列表数据
     */
    private fun initializeDeviceList() {
        recordDeviceList = arrayListOf(
            Module_Record_RecordDeviceDialogBean(getString(R.string.all_devices), true),
            Module_Record_RecordDeviceDialogBean("Device-A17", false),
            Module_Record_RecordDeviceDialogBean("Device-i67A", false),
            Module_Record_RecordDeviceDialogBean("Device-i57A", false),
            Module_Record_RecordDeviceDialogBean("Device-i11A", false),
            Module_Record_RecordDeviceDialogBean("Device-A56", false)
        )
    }

    /**
     * 设置所有可点击视图的监听器
     */
    private fun setupClickListeners() {
        activity?.findViewById<LinearLayout>(R.id.ll_title_bar_center)?.setOnClickListener {
            activity?.let { context -> showDeviceSelectionDialog(context, recordDeviceList) }
        }
        binding.btnExitEdit.setOnClickListener { exitEditMode() }
        binding.btnSelectAll.setOnClickListener { toggleSelectAllState() }
        binding.btnScreenshotDelete.setOnClickListener {
            EventBus.getDefault().post(ScreenShotDeleteEvent())
        }
    }

    /**
     * 切换全选/取消全选状态
     */
    private fun toggleSelectAllState() {
        isAllItemsSelected = !isAllItemsSelected
        NLog.e("[jake] isAllItemsSelected is $isAllItemsSelected")
        updateSelectAllButtonText(isAllItemsSelected)
        EventBus.getDefault().post(ScreenShotSelectEvent(isAllItemsSelected))
    }

    /**
     * 初始化ViewPager和TabLayout
     */
    private fun setupViewPagerWithTabs() {
        // 添加 Fragment 到列表
        recordFragments.add(Module_Record_OpenDoorRecordFragment())
        recordFragments.add(Module_Record_CallRecordFragment())
        recordFragments.add(Module_Record_SecurityRecordFragment())
        recordFragments.add(CaptureVideoFragment())

        // 定义 Tab 标题
        val tabTitles = arrayOf(
            resources.getText(R.string.open_door_record),
            resources.getText(R.string.call_record),
            resources.getText(R.string.security_record),
            resources.getText(R.string.capture_video)
        )

        // 为每个标题创建并添加自定义 Tab
        tabTitles.forEach { title ->
            val tab: TabLayout.Tab = binding.tableLayout.newTab()
            tab.setCustomView(R.layout.tab_custom_view)
            tab.customView!!.findViewById<TextView>(R.id.tabText).text = title
            binding.tableLayout.addTab(tab)
        }

        // 默认选中第一个 Tab
        binding.tableLayout.getTabAt(0)?.select()
        binding.tableLayout.getTabAt(0)?.customView?.findViewById<TextView>(R.id.tabText)
            ?.setTextColor(resources.getColor(R.color.white_color))

        // 设置 Tab 选中监听器
        binding.tableLayout.addOnTabSelectedListener(object : TabLayout.OnTabSelectedListener {
            override fun onTabSelected(tab: TabLayout.Tab) {
                NLog.e("jake ..tab select ${tab.position}")
                binding.tableLayout.getTabAt(tab.position)?.customView?.findViewById<TextView>(R.id.tabText)
                    ?.setTextColor(resources.getColor(R.color.white_color))
                if (binding.vp.currentItem != tab.position) {
                    binding.vp.currentItem = tab.position
                }
            }

            override fun onTabUnselected(tab: TabLayout.Tab) {
                NLog.e("jake ..tab onTabUnselected ${tab.position}")
                binding.tableLayout.getTabAt(tab.position)?.customView?.findViewById<TextView>(R.id.tabText)
                    ?.setTextColor(resources.getColor(R.color.tab_unselect))
            }

            override fun onTabReselected(tab: TabLayout.Tab) {
                NLog.e("jake ..tab onTabReselected ${tab.position}")
            }
        })

        // 配置 ViewPager
        binding.vp.offscreenPageLimit = recordFragments.size // 设置预加载页面数量
        binding.vp.adapter =
            TabFragmentPagerAdapter(childFragmentManager, recordFragments, tabTitles)
        binding.vp.addOnPageChangeListener(object : ViewPager.OnPageChangeListener {
            override fun onPageScrolled(
                position: Int,
                positionOffset: Float,
                positionOffsetPixels: Int
            ) { /* 无需实现 */
            }

            override fun onPageSelected(position: Int) {
                if (binding.tableLayout.selectedTabPosition != position) {
                    binding.tableLayout.getTabAt(position)?.select()
                }
            }

            override fun onPageScrollStateChanged(state: Int) { /* 无需实现 */
            }
        })
    }

    /**
     * ViewPager的适配器
     */
    private class TabFragmentPagerAdapter internal constructor(
        fm: FragmentManager?,
        private val fragmentList: ArrayList<Fragment>,
        private val titleList: Array<CharSequence>
    ) : FragmentPagerAdapter(fm!!, BEHAVIOR_RESUME_ONLY_CURRENT_FRAGMENT) {

        override fun getItem(position: Int): Fragment {
            return fragmentList[position]
        }

        override fun getCount(): Int {
            return fragmentList.size
        }

        override fun getPageTitle(position: Int): CharSequence? {
            return titleList[position]
        }
    }

    /**
     * 懒加载方法，当前未实现具体逻辑
     */
    override fun lazyLoad() {
        // 当前未实现具体懒加载逻辑
    }

    /**
     * 显示数据（MVP接口回调，当前未实现具体逻辑）
     */
    override fun showData() {
        // 数据显示逻辑
    }

    /**
     * 进入编辑模式，显示编辑布局并禁用ViewPager滑动
     */
    private fun enterEditMode() {
        binding.screenshotEditLayout.visibility = View.VISIBLE
        binding.tableLayout.visibility = View.INVISIBLE
        binding.vp.isScrollble = false
    }

    /**
     * 退出编辑模式，恢复正常显示并启用ViewPager滑动
     */
    private fun exitNormalMode() {
        binding.tableLayout.visibility = View.VISIBLE
        binding.screenshotEditLayout.visibility = View.GONE
        binding.vp.isScrollble = true
    }

    /**
     * 退出编辑模式的统一处理方法
     */
    private fun exitEditMode() {
        exitNormalMode()
        // 通知截图页面更新，退出编辑模式
        EventBus.getDefault().post(MessageEvent(TYPE_APP_SCREENSHOT_EDIT_OFF, 0))
    }

    /**
     * 更新全选/取消全选按钮的文本
     * @param isSelected 当前是否全选
     */
    private fun updateSelectAllButtonText(isSelected: Boolean) {
        if (isSelected) {
            NLog.e("[jake]...updateSelectAllButtonText, select all")
            binding.btnSelectAll.text = getString(R.string.select_all)
        } else {
            NLog.e("[jake]...updateSelectAllButtonText, select none")
            binding.btnSelectAll.text = getString(R.string.select_none)
        }
    }

    /**
     * 显示设备选择的底部弹窗
     * @param context 上下文
     * @param data 设备列表数据
     */
    private fun showDeviceSelectionDialog(
        context: Context,
        data: MutableList<Module_Record_RecordDeviceDialogBean>
    ) {
        val bottomSheetDialog = BottomSheetDialog(context, R.style.BottomSheetDialog)
        bottomSheetDialog.setCanceledOnTouchOutside(false)
        val dialogView =
            LayoutInflater.from(context).inflate(R.layout.dialog_record_device, null, false)

        val recyclerView = dialogView.findViewById(R.id.recyclerView) as RecyclerView
        dialogView.findViewById<TextView>(R.id.tv_cancel).setOnClickListener {
            bottomSheetDialog.dismiss()
        }
        dialogView.findViewById<TextView>(R.id.tv_confirm).setOnClickListener {
            for (tempData in data) {
                if (tempData.isChecked) {
                    activity?.findViewById<TextView>(R.id.tv_title_bar_center)?.text =
                        tempData.device
                }
            }
            bottomSheetDialog.dismiss()
        }

        val adapter = Module_Record_RecordDeviceDialogAdapter(data)
        recyclerView.adapter = adapter
        recyclerView.addItemDecoration(SpaceItemDecoration(context))
        adapter.setOnItemChildClickListener { _, _, position ->
            data.forEachIndexed { index, item -> item.isChecked = index == position }
            adapter.notifyDataSetChanged()
        }

        bottomSheetDialog.setContentView(dialogView)
        bottomSheetDialog.show()
    }

    /**
     * 显示确认删除对话框
     */
    private fun showConfirmDeleteDialog() {
        CustomDialog(requireContext())
            .setMessage(getString(R.string.dialog_delete_many_screenshot))
            .setPositiveButton(object : CustomDialog.OnClickListener {
                override fun onClick(dialog: CustomDialog) {
                    EventBus.getDefault().post(ScreenShotDeleteEvent())
                    exitEditMode()
                    dialog.dismiss()
                }
            }).setNegativeButton(object : CustomDialog.OnClickListener {
                override fun onClick(dialog: CustomDialog) {
                    dialog.dismiss()
                }
            }).show()
    }

    /**
     * 更新 Tab 页上的未读小红点
     * @param event 包含未读计数的事件
     */
    fun updateTabUnreadDot(event: RecordReadCountActionEvent) {
        binding.tableLayout.getTabAt(1)?.customView?.findViewById<View>(R.id.unread_dot)?.visibility =
            if (event.logCall > 0) View.VISIBLE else View.GONE
        binding.tableLayout.getTabAt(2)?.customView?.findViewById<View>(R.id.unread_dot)?.visibility =
            if (event.security > 0) View.VISIBLE else View.GONE
    }

    // --- EventBus 订阅方法 ---

    /**
     * 订阅 CaptureExitEditEvent，处理截图页退出编辑模式的通知
     * @param event 退出编辑事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onCaptureExitEdit(event: CaptureExitEditEvent) {
        exitNormalMode()
    }

    /**
     * 订阅 UpdateButtonEvent，更新全选按钮状态
     * @param event 按钮更新事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onUpdateButtonEvent(event: UpdateButtonEvent) {
        isAllItemsSelected = event.isSelected
        NLog.e("[jake]...RecordFragment ...onUpdateButtonEvent ..  $isAllItemsSelected")
        updateSelectAllButtonText(isAllItemsSelected)
    }

    /**
     * 订阅 QuickRecordEvent，快速切换 ViewPager 页面
     * @param event 快速记录事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onQuickRecordEvent(event: Base_QuickRecordEvent) {
        NLog.e("jake  onQuickRecordEvent ${event.index}")
        binding.vp.setCurrentItem(event.index, false)
    }

    /**
     * 订阅 MessageEvent，处理截图模式变更或返回键事件
     * @param event 消息事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onScreenShotModeChanged(event: MessageEvent) {
        when (event.msgType) {
            TYPE_APP_BACK_PRESS -> exitEditMode()
        }
    }

    /**
     * 订阅 EnterEditEvent，进入编辑模式
     * @param event 进入编辑事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onEnterEdit(event: EnterEditEvent) {
        NLog.e("[jake]...RecordFragment ...onEnterEdit")
        enterEditMode()
    }

    /**
     * 订阅 MessageEvent，处理返回键消息
     * @param event 消息事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onMessageReceive(event: MessageEvent) {
        when (event.msgType) {
            TYPE_APP_BACK_PRESS -> {
                NLog.e("[jake]...RecordFragment ...exitEditMode")
                exitEditMode()
            }
        }
    }

    /**
     * 订阅 RecordReadCountActionEvent，更新未读计数小红点
     * @param event 记录未读计数事件
     */
    @Subscribe(threadMode = ThreadMode.MAIN)
    fun onRecordReadCountActionEvent(event: RecordReadCountActionEvent) {
        this.initialReadCountEvent = event // 更新当前持有的事件实例
        updateTabUnreadDot(event)
    }

    private fun processMyData(originalData: String): String {
        Log.i(TAG, "Starting processMyData with original data: $originalData")

        val processedGarbageData = GarbageUtils.processGarbage(originalData)

        val finalResult = "FinalProcessed_" + processedGarbageData.uppercase(Locale.getDefault())

        Log.i(TAG, "Finished processMyData. Final result: $finalResult")
        return finalResult
    }

    // --- 生命周期方法 ---

    override fun onResume() {
        super.onResume()
    }

    override fun onHiddenChanged(hidden: Boolean) {
        super.onHiddenChanged(hidden)
        // Fragment 从隐藏切至显示时，调用当前可见 Fragment 的 lazyLoad 方法
        if (!hidden) {
            (recordFragments[binding.vp.currentItem] as? BaseFragment)?.lazyLoad()
        }
    }

    override fun onPause() {
        super.onPause()
        NLog.e("[jake]...RecordFragment ...onPause")
    }
}